import { Component, OnInit, ViewChild, TemplateRef, OnDestroy } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { Subscription, zip, of, Observable } from 'rxjs'
import { switchMap, take, tap } from 'rxjs/operators'

import { DataService } from '@shared/services/data.service'
import { PageService } from '@shared/services/page.service'
import { StoreService } from '../../store.service'
import { DetailTabClass } from '@shared/classes/DetailTabClass'
import { IBaseInfoColumn } from '@shared/interfaces/baseInfo'
import { ETabScrollStatus } from '@shared/enums'
import { Store, StoreQRFeature, StoreQRFeatureUpdate, StoreFull } from '@shared/interfaces/store'
import { I18NService } from '@core'

@Component({
  selector: 'app-store-tab-qr-function',
  templateUrl: './tab-qr-function.component.html',
})
export class StoreDetailTabQRFunctionComponent extends DetailTabClass<StoreQRFeature> implements OnInit, OnDestroy {
  constructor(
    private dataService: DataService,
    private storeService: StoreService,
    private i18n: I18NService,
    public pageService: PageService,
    public route: ActivatedRoute,
  ) {
    super(pageService, route)
  }

  private subscription: Subscription
  private store: Store
  private storeFull: StoreFull

  @ViewChild('tpRefundMode') tpRefundMode: TemplateRef<any>
  @ViewChild('tpIsSupportTips') tpIsSupportTips: TemplateRef<any>
  @ViewChild('tpTradeOperate') tpTradeOperate: TemplateRef<any>

  fields = {
    TradeFunction: '1',
  }

  get isNeedDiff(): boolean {
    return this.dataService.isNeedDiff
  }

  ngOnInit(): void {
    this.initialColumns()
    this.initialData()
  }

  initialData() {
    const { origStore, currentStore } = this.dataService
    if (this.isNeedDiff) this.origData = origStore.qr

    this.subscription = this.dataService.storeFull$.value$
      .pipe(
        take(1),
        tap(full => {
          this.storeFull = full
        }),
        switchMap(full => (this.isNeedDiff ? of(currentStore) : of(full.store))),
      )
      .subscribe(store => {
        this.store = store
        if (!store.qr.isRefundAsync) {
          store.qr.isRefundAsync = false
        }
        this.data = store.qr
        this.setEdit(this.fields.TradeFunction, 1)

        this.createTradeFunctionColumns(this.data)
          .pipe(switchMap(this.checkColumnsDiff))
          .subscribe(columns => {
            this.columns[this.fields.TradeFunction].push(columns)
            this.setupIdForColumn(this.fields)
          })
      })
    this.pageService.setTabScrollStatus(ETabScrollStatus.Scroll)
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe()
  }

  checkColumnsDiff = (columns: IBaseInfoColumn[]): Observable<IBaseInfoColumn[]> => {
    /** 如果不需要Diff，直接返回false */
    const { isNeedDiff } = this.dataService
    if (!isNeedDiff) return of(columns)
    return this.getDiffedColumns(columns)
  }

  private createTradeFunctionColumns(feature: StoreQRFeature): Observable<IBaseInfoColumn[]> {
    return zip(this.pageService.isStoreDisplayInTask$, this.pageService.isStoreLocked$).pipe(
      take(1),
      switchMap(result => {
        const [isStoreDisplayInTask, isStoreLocked] = result
        const operateColumn =
          !isStoreDisplayInTask && !isStoreLocked
            ? [
                {
                  span: 4,
                  label: 'GENERAL.INFO.OPERATION',
                  labelI18n: 'GENERAL.INFO.OPERATION',
                  operate: true,
                  template: this.tpTradeOperate,
                  acl: ['api.put.zebra.store.one.feature'],
                },
              ]
            : []
        const span = !isStoreDisplayInTask && !isStoreLocked ? 10 : 12
        return of([
          {
            span,
            label: 'BIZ.STORE.OTHER.TRADE.REFUND_MODE',
            labelI18n: 'BIZ.STORE.OTHER.TRADE.REFUND_MODE',
            index: 'isRefundAsync',
            value: feature.isRefundAsync
              ? this.trans('BIZ.STORE.OTHER.TRADE.REFUND_MODE.ASYNC')
              : this.trans('BIZ.STORE.OTHER.TRADE.REFUND_MODE.SYNC'),
            template: this.tpRefundMode,
          },
          {
            span,
            label: 'BIZ.STORE.OTHER.TRADE.TIPS_INSIDE_QRCODE',
            labelI18n: 'BIZ.STORE.OTHER.TRADE.TIPS_INSIDE_QRCODE',
            index: 'isSupportTips',
            value: feature.isSupportTips ? this.trans('GENERAL.INFO.YES') : this.trans('GENERAL.INFO.NO'),
            template: this.tpIsSupportTips,
          },
          ...operateColumn,
        ])
      }),
    )
  }

  // abstract methods
  onCancel() {}

  onSubmit() {
    const d = new StoreQRFeatureUpdate(this.store.version)
    d.feature.isRefundAsync = this.data.isRefundAsync
    d.feature.isSupportTips = this.data.isSupportTips

    const token = this.dataService.token
    this.storeService
      .updateQRFeature(this.store.common.intStoreCode, token, d)
      .pipe(take(1))
      .subscribe(result => {
        this.isEdits[this.field][this.rowIndex] = false
        if (!(result instanceof StoreFull)) {
          return
        }

        if (result.store.version) {
          this.store.version = result.store.version
        }

        this.storeFull.store = result.store
        this.dataService.setStoreFull(this.storeFull)
        this.initialColumns()
        this.initialData()
      })
  }

  initialColumns() {
    /*
     * 这个columns是用来收集所有需要display在这个tab里面的数据.
     * 比如 "交易币种转换" = '1', 然后交易币种转换里有一个Array = [商户交易币种, 转换交易币种, 转换汇率, 等等] 然后他在columns里就是
     * {'1': [[{商户交易币种, 转换交易币种, 转换汇率, 等等}]]}
     */
    // 现在这个trades component需要展示2个field. 这里创建2个空的Array在this.columns里的field
    for (const key in this.fields) {
      this.columns[this.fields[key]] = []
    }
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
